package com.tfjybj.itoo.exam.websocket;

import com.tfjybj.itoo.exam.model.ExamineeModel;
import com.tfjybj.itoo.exam.provider.service.ExamineeService;
import com.tfjybj.itoo.exam.provider.service.impl.ExamineeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ContextLoader;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;


@ServerEndpoint(value = "/sentmessage")
@RestController
@Slf4j
public class SendMessageController {
    @Resource
    private ExamineeService examineeService;

    private ExamineeService aaa=new ExamineeServiceImpl();



    private static final String GUEST_PREFIX = "Guest";
    private static final AtomicInteger connectionIds = new AtomicInteger(0);
    private static final Set<SendMessageController> connections =   new CopyOnWriteArraySet<>();
    private final String Username;
    private Session session;

    public SendMessageController() {
        Username = GUEST_PREFIX + connectionIds.getAndIncrement();
    }
    @OnOpen
    public void start(Session session) {
        this.session = session;
        connections.add(this);
        String message = String.format("* %s %s", Username, "has joined.");
//        System.out.println(message);
        broadcast(message);
    }


    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("* %s %s",
                Username, "has disconnected.");
        broadcast(message);
    }


    @OnMessage
    public void incoming( String message) {
        ExamineeService examineeService = (ExamineeService) ContextLoader.getCurrentWebApplicationContext().getBean("examineeService");

       String json = message;
//
        String[] split = message.substring(message.indexOf("{")+1,message.lastIndexOf("}")).split(",");

       String examinationId=(split[0].replaceAll("\"","").split(":")[1]);
        String classId = (split[1].replaceAll("\"","").split(":")[1]);
        List<ExamineeModel> examineeModelList1 = examineeService.queryChapterNumbe(examinationId, classId);

        String[] strings =  new String[examineeModelList1.size()];
        for (int i = 0 ; i<examineeModelList1.size(); i++){
            strings[i] =examineeModelList1.get(i).toString();
            System.out.println("学生信息："+  strings[i] );
        }
        for (String s :strings ) {
            String splits = s.substring(s.indexOf("studentCode") + 12, s.indexOf("className") - 2);
            broadcast(splits);


        }
    }

//

    @OnError
    public void onError(Throwable t) {

    }


    private static void broadcast(String msg) {
        for (SendMessageController client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s",
                        client.Username, "has been disconnected.");
                broadcast(message);
            }
        }
    }
}
